package cn.tedu.submarine;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class World extends JPanel {
    public static final int WIDTH = 641;
    public static final int HEIGHT = 479;
    public static final int RUNNING = 0;//运行状态
    public static final int PAUSE = 1;//暂停状态
    public static final int GAME_OVER = 2;//游戏介绍状态
    private int state = RUNNING;//当前状态（默认是运行状态）
    private Battleship ship = new Battleship();
    private SeaObject[] submarines = {};
    private Mine[] mines = {};
    private Bomb[] bombs = {};
    /**生成潜艇*/
    private SeaObject nextOne(){
        Random rand = new Random();
        int type = rand.nextInt(20);//0~9
        if (type < 10) {
            return new ObserveSubmarine();
        } else if (type < 16) {//10~15
            return new MineSubmarine();
        }else{//16~19
            return new TorpedoSubmarine();
        }
    }
    /**潜艇入场*/
    private int subEnterIndex = 0;
    private void submarinesEnterAction(){//10毫秒运行一次
        subEnterIndex++;
        if (subEnterIndex%40 == 0) {
            SeaObject obj = nextOne();
            submarines = Arrays.copyOf(submarines,submarines.length+1);
            submarines[submarines.length-1] = obj;//将obj添加到最后一个元素上
        }

    }
    /** 水雷入场*/
    private int mineEnterIndex = 0;
    private void mineEnterAction(){
        mineEnterIndex++;
        if (mineEnterIndex%100 == 0) {
            for (int i = 0; i < submarines.length; i++) {//遍历所有的潜艇
                if (submarines[i] instanceof MineSubmarine) {
                    MineSubmarine ms = (MineSubmarine)submarines[i];//潜艇强转为水雷艇
                    Mine obj = ms.shootMine();
                    mines = Arrays.copyOf(mines,mines.length+1);
                    mines[mines.length-1] = obj;
                }

            }

        }
    }
    /**  移动*/
    public void moveAction(){
        for (int i = 0; i < submarines.length; i++) {
            submarines[i].move();
        }
        for (int i = 0; i < mines.length; i++) {
            mines[i].move();
        }
        for (int i = 0; i < bombs.length; i++) {
            bombs[i].move();
        }
    }
    /** 删除越界对象 */
    private void outOfBoundsAction(){
        for (int i = 0; i < submarines.length; i++) {
            if (submarines[i].isOutOfBounds() || submarines[i].isDead()) {
                submarines[i] = submarines[submarines.length-1];
                submarines = Arrays.copyOf(submarines,submarines.length-1);
            }
        }
        for (int i = 0;i<mines.length;i++){
            if (mines[i].isOutOfBounds() || mines[i].isDead()) {
                mines[i] = mines[mines.length-1];
                mines = Arrays.copyOf(mines,mines.length-1);
            }
        }
        for (int i = 0;i<bombs.length;i++){
            if (bombs[i].isOutOfBounds() || bombs[i].isDead()) {
                bombs[i] = bombs[bombs.length-1];
                bombs = Arrays.copyOf(bombs,bombs.length-1);
            }
        }
    }
    private int score = 0;   //玩家得分
    /** 炸弹和潜艇的碰撞 */
    private void bombBangAction(){//10毫秒运行一次
        for (int i = 0; i < bombs.length; i++) {
            Bomb b = bombs[i];//遍历每个炸弹
            for (int j = 0; j < submarines.length; j++) {
                SeaObject s = submarines[j];//遍历每个潜艇
                if (b.isLive() && s.isLive() && s.isHit(b)) {
                    s.goDead();
                    b.goDead();
                    if (s instanceof EnemyScore) {
                        EnemyScore es = (EnemyScore)s;
                        score += es.getScore(); //玩家得分
                    }
                    if (s instanceof EnemyLife) {
                        EnemyLife el = (EnemyLife)s;
                        int num = el.getLife();
                        ship.addLife(num); //战舰增命
                    }
                }
            }
        }
    }
    /**   水雷战舰碰撞 */
    private void mineBangAction(){
        for (int i = 0; i < mines.length; i++) {
            Mine m = mines[i];
            if (m.isLive() && ship.isLive() && m.isHit(ship)) {
                m.goDead();
                ship.subtractLife();
            }
        }
    }
    /** 游戏介绍 */
    private void checkGameOverAction(){
        if (ship.getLife() <= 0) {
            state = GAME_OVER;//当前状态修改为游戏结束状态
        }
    }
    /** 启动程序*/
    public void action(){
        KeyAdapter k = new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_P){
                    if (state == RUNNING){//运行状态时修改为暂停状态
                        state = PAUSE;
                    } else if (state == PAUSE) {
                        state = RUNNING;
                    }
                }
                if (state == RUNNING) {
                    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                        Bomb obj = ship.shootBomb();
                        bombs = Arrays.copyOf(bombs,bombs.length+1);
                        bombs[bombs.length-1] = obj;
                    }
                    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                        ship.moveLeft();
                    }
                    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                        ship.moveRight();
                    }
                }
            }
        };//键盘侦听器
        this.addKeyListener(k);
        Timer timer = new Timer();//定时器对象
        int interval = 10;//定时间隔  以毫秒为单位
        timer.schedule(new TimerTask() {
            public void run() {
                if (state == RUNNING) {
                    submarinesEnterAction();//潜艇
                    mineEnterAction();//水雷
                    moveAction();//海洋对象移动
                    outOfBoundsAction();//删除越界的海洋对象
                    bombBangAction(); //炸弹碰潜艇
                    mineBangAction();
                    checkGameOverAction();
                    repaint();//重画-------重新调用paint()方法
                }

            }
        }, interval, interval);//定时计划表

    }
    /** 画对象   g:画笔*/
    public void paint(Graphics g){
        Images.sea.paintIcon(null,g,0,0);
        ship.paintImage(g);
        for (int i = 0; i < submarines.length; i++) {
            submarines[i].paintImage(g);
        }
        for (int i = 0; i < mines.length; i++) {
            mines[i].paintImage(g);
        }
        for (int i = 0; i < bombs.length; i++) {
            bombs[i].paintImage(g);
        }
        g.drawString("得分:"+score,200,50);//分
        g.drawString("命:"+ship.getLife(),400,50 );
        if (state == GAME_OVER) {
            Images.gameover.paintIcon(null,g,0,0);
        }
    }

    /** 游戏窗口*/
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        World world = new World();
        world.setFocusable(true);
        frame.add(world);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH+16,HEIGHT+39);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);

        world.action();
    }

}
